package com.lottery.im.module.tim.event;

import com.lottery.im.module.tim.message.GroupTipMessage;
import com.lottery.im.module.tim.message.Message;
import com.lottery.im.module.tim.message.MessageFactory;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.ext.message.TIMConversationExt;
import com.tencent.imsdk.ext.message.TIMMessageLocator;
import com.tencent.imsdk.ext.message.TIMMessageRevokedListener;
import com.tencent.imsdk.ext.message.TIMUserConfigMsgExt;
import java.util.List;
import java.util.Observable;

/**
 * 消息通知事件，上层界面可以订阅此事件
 */
public class MessageEvent extends Observable
    implements TIMMessageListener, TIMMessageRevokedListener {

  private volatile static MessageEvent instance;

  private MessageEvent() {
    //注册消息监听器
    TIMManager.getInstance().addMessageListener(this);
  }

  public TIMUserConfig init(TIMUserConfig config) {
    TIMUserConfigMsgExt ext = new TIMUserConfigMsgExt(config);
    ext.enableRecentContact(false)
        .enableAutoReport(false)
        .setMessageRevokedListener(this);
    return ext;
  }

  public static MessageEvent getInstance() {
    if (instance == null) {
      synchronized (MessageEvent.class) {
        if (instance == null) {
          instance = new MessageEvent();
        }
      }
    }
    return instance;
  }

  @Override
  public boolean onNewMessages(List<TIMMessage> list) {

    if (null != list && list.size() > 0 && list.get(0).getElementCount() > 0) {

      if (list.get(0).getElement(0).getType() == TIMElemType.GroupTips) {

        Message mMessage = MessageFactory.getMessage(list.get(0));
        if (mMessage.getSummary().equals(GroupTipMessage.NO_TIP_TEXT)) {
          TIMConversation conversation = list.get(0).getConversation();
          TIMConversationExt conExt = new TIMConversationExt(conversation);
          if (conExt.getUnreadMessageNum() == 1) {
            conExt.setReadMessage(list.get(0), null);
          }

          mMessage.remove();
          return false;
        }
      }
    }

    for (TIMMessage item : list) {
      setChanged();
      notifyObservers(item);
    }
    return false;
  }

  /**
   * 主动通知新消息
   */
  public void onNewMessage(TIMMessage message) {
    setChanged();
    notifyObservers(message);
  }

  /**
   * 清理消息监听
   */
  public void clear() {
    instance = null;
  }

  @Override
  public void onMessageRevoked(TIMMessageLocator timMessageLocator) {
    setChanged();
    notifyObservers(timMessageLocator);
  }
}
